﻿using System;
using System.IO;
using System.Windows.Forms;

namespace phhui
{
    class FileHelper
    {
        /// <summary>The command is executed success</summary>
        public const int CMD_OK= 1;
        ///<summary>The file is no found</summary>
        public const int CMD_FAILE_NO_FOUND = 0;
        ///<summary>The file is using</summary>
        public const int CMD_FAILE_IN_USE = 2;
        ///<summary>The file already exists</summary>
        public const int CMD_FILE_ALREADY_EXISTS = 3;
        ///<summary>The path is no a valid directory</summary>
        public const int CMD_PATH_NO_DIRECTORY = 4;

        public const int CMD_TYPE_IMG = 10;

        public const int CMD_TYPE_TXT = 11;

        public const int CMD_TYPE_OTHER = 12;
        public static int deleteFile(string path)
        {
            if (!File.Exists(path)){return CMD_FAILE_NO_FOUND; }
            if (IsFileInUse(path)) { return CMD_FAILE_IN_USE; }
            File.Delete(path);
            return CMD_OK;
        }
        public static int moveFile(string path,string newPath)
        {
            if (!File.Exists(path)){return CMD_FAILE_NO_FOUND; }
            if (IsFileInUse(path)) { return CMD_FAILE_IN_USE; }
            if (File.Exists(newPath)) { return CMD_FILE_ALREADY_EXISTS; }
            if(path!=newPath)File.Move(path, newPath);
            return CMD_OK;
        }
        public static FileListDetails getFileList(string path,Boolean containChild)
        {
            return new FileListDetails(path, containChild);
        }
        public static bool IsFileInUse(string fileName)
        {
            bool inUse = true;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,FileShare.None);
                inUse = false;
            }catch{}
            finally{
                if (fs != null)
                    fs.Close();
            }
            return inUse;//true表示正在使用,false没有使用  
        }
        public static int checkType(string url)
        {
            string type = url.Substring(url.LastIndexOf(".")+1).ToLower(); ;
            if (type == "jpg" || type == "jpeg" || type == "png" || type == "bmp" || type == "gif")
            {
                return CMD_TYPE_IMG;
            }
            if((type == "txt" || type == "js" || type == "cs" || type == "as" || type == "html" || type == "java" || type == "cpp" || type == "xml" || type == "json"))
            {
                return CMD_TYPE_TXT;
            }
            return CMD_TYPE_OTHER;
        }
    }
}
